import java.util.Arrays;

public class TestHeap {
    private int[] elem;
    private int usedSize;
    public TestHeap(){
        elem = new int[10];
    }
    public void initHeap(int[] array){
        for(int i = 0; i < elem.length; i++){
            elem[i] = array[i];
            usedSize++;
        }
    }
    public void createHeap(){
        for(int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--){
            shiftDown(parent, usedSize);
        }
    }
    public void shiftDown(int parent, int usedSize){
        int child = 2 * parent + 1;//左孩子下标
        while(child < usedSize){
            //求左右孩子最大值的下标
            if(child + 1 < usedSize && elem[child] < elem[child + 1]){
                child++;
            }
            //child是左右孩子最大值的下标
            if(elem[parent] < elem[child]){
                swap(parent, child);
                parent = child;
                child = 2 * parent + 1;
            }else{
                //已经是大根堆了
                break;
            }
        }
    }

    private boolean isFull(){
        return usedSize == elem.length;
    }
    public void offer(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }
    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while(child > 0){
            if(elem[child] > elem[parent]){
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            }else{
                break;
            }
        }
    }

    public int poll(){
        int tmp = elem[0];
        swap(0, usedSize-1);
        usedSize--;
        shiftDown(0, usedSize);
        return tmp;
    }
    private void swap(int i, int j){
        int temp = elem[i];
        elem[i] = elem[j];
        elem[j] = temp;
    }
}
